package org.example.service;
import lombok.RequiredArgsConstructor;
import org.example.entity.DateTimeUtils;
import org.example.entity.MeetingStatisticsDTO;
import org.example.entity.TrendDataDTO;
import org.example.mapper.MeetingMapper;
import org.example.mapper.MeetingRoomMapper;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;


@Service
@RequiredArgsConstructor
public class MeetingStatisticsServiceImpl implements MeetingStatisticsService {
    private final MeetingMapper meetingMapper;
    private final MeetingRoomMapper meetingRoomMapper;

    @Override
    public MeetingStatisticsDTO getCoreStatistics(String statType) {
        MeetingStatisticsDTO dto = new MeetingStatisticsDTO();

        // 使用时间工具类获取周期时间范围
        LocalDateTime endTime = LocalDateTime.now();
        LocalDateTime startTime = DateTimeUtils.getStartTimeByStatType(statType, endTime);

        // 调用Mapper层获取统计数据
        Integer totalMeetings = meetingMapper.countTotalMeetings(startTime, endTime);
        dto.setTotalMeetings(totalMeetings);

        Integer usedHours = meetingMapper.countUsedRoomHours(startTime, endTime);
        long roomCount = meetingRoomMapper.selectCount(null);
        // 使用工具类计算周期天数
        long totalDays = DateTimeUtils.calculateDaysBetween(startTime, endTime);
        long totalAvailableHours = 8L * totalDays * roomCount;
        dto.setRoomUsageRate(totalAvailableHours > 0 && usedHours != null ?
                (usedHours * 100.0) / totalAvailableHours : 0.0);

        dto.setOverdueMeetings(meetingMapper.countOverdueMeetings(startTime, endTime));

        Integer fullAttendanceMeetings = meetingMapper.countFullAttendanceMeetings(startTime, endTime);
        dto.setFullAttendanceRate(totalMeetings > 0 && fullAttendanceMeetings != null ?
                (fullAttendanceMeetings * 100.0) / totalMeetings : 0.0);
        // 新增：计算全勤参会人数（平均）
        Integer fullAttendancePeopleTotal = meetingMapper.countFullAttendancePeople(startTime, endTime);
        dto.setFullAttendancePeople(fullAttendanceMeetings != null && fullAttendanceMeetings > 0 && fullAttendancePeopleTotal != null
                ? (fullAttendancePeopleTotal * 1.0) / fullAttendanceMeetings // 总人数 / 全勤会议数 = 平均人/场
                : 0.0);
        return dto;
    }

    // 正确逻辑：若查询结果为null，返回空数组（避免前端接收null）
    @Override
    public List<TrendDataDTO> getTrendData(String statType) {
        List<TrendDataDTO> trendData = meetingMapper.getTrendData(statType);
        return trendData == null ? Collections.emptyList() : trendData; // 关键：确保返回数组
    }
}